<?php
namespace Modules;
use Admin\Models\ims\XHImsBoxIn;
use Admin\Models\ims\XHImsBoxOut;
use Admin\Models\ims\XHImsProduce;
use Admin\Models\ims\XHImsProduceIn;
use Admin\Models\ims\XHImsProduceOut;
use Admin\Models\ims\XHImsProduceType;
use Admin\Models\ims\XHImsProduct;
use Helpers\Tool;
use Helpers\XhException;
use Phalcon\Di;

class Ims{

    /**
     * 入库记录保存
     *
     * @param $data
     * @param $keyMap
     * @param string $mark
     * @param null $userId
     * @return bool
     * @throws XhException
     * create by xjq 20180621
     * modify by dale 20180718  弃用
     */
    public static function resIn($data , $keyMap=[] , $mark='' , $userId = null){
        $box = new XHImsBoxIn();
        $box->assign($data);
        foreach ($keyMap as $key => $map){
            $box->$key = $data[$map];
        }
        if(!$box->iTypeId){
            $box->iTypeId = XHImsProduct::getProdTypeById($box->iProdId);
        }
        $box->iState = 1;
        $box->sRemark = $box->sRemark ?: $mark;
        if($userId){
            $box->iCreateUserId     = $userId;
            $box->iLastModifyUserId = $userId;
        }
        if (!$box->save()){
            throw new XhException('入库保存失败');
        }
        return true;
    }

    /**
     *
     * @param $data
     * @param $keyMap
     * @param string $mark
     * @param null $userId
     * @return bool
     * @throws XhException
     *
     * create by xjq 20180621
     * modify by dale 20180718  弃用
     */
    public static function resOut($data , $keyMap=[] , $mark='' , $userId = null){
        $box = new XHImsBoxOut();
        $box->assign($data);
        foreach ($keyMap as $key => $map){
            $box->$key = $data[$map];
        }
        if(!$box->iTypeId){
            $box->iTypeId = XHImsProduct::getProdTypeById($box->iProdId);
        }
        $box->iType = 2;
        $box->sRemark = $box->sRemark ?: $mark;
        if ($userId) {
            $box->iCreateUserId  = $userId;
            $box->iLastModifyUserId = $userId;
        }
        if (!$box->save()){
            throw new XhException('出库保存失败');
        }
        return true;
    }

    /**
     * 获取商品通过名称
     *
     * @param $name
     * @param bool $onlyKeyValue
     * @param bool $onlyId
     * @return array
     * @throws XhException
     *
     * create by xjq 20180625
     * modify by dale 20180803  数据库迁移，数据库修改
     */
    public static function getProdsByTypeName($name , $onlyKeyValue=true ,$onlyId = false)
    {
        $data = Di::getDefault()->get('db')->fetchAll("select iProdId,sProdName,iPTId,sMeasure from XHIms_Produce where bDelete =0 and iPTId in (select iPTId from XHIms_ProduceType where sType = '{$name}' )");
        if (!$data) {
            throw new XhException("获取{$name}类型下的商品失败,请检查该商品类型是否创建");
        }
        if ($onlyId) {
            return array_values(array_filter(array_column($data, 'iProdId')));
        }
        return $onlyKeyValue ? array_column($data , 'sProdName' , 'iProdId') : $data;
    }

    /**
     * 获取商品库存
     *
     * @param $prodId
     *
     * @return int
     * @throws XhException
     *
     * create by dale  20180718
     */
    public static function getProdCurrentNum($prodId)
    {
        $prod = XHImsProduce::findFirst($prodId);
        if (!$prod) {
            throw new XhException("该商品不存在");
        }
        return $prod->iCurrentNum ?: 0;
   }


    /**
     * 入库保存
     *
     * @param $data
     * @param array $keyMap
     * @param string $mark
     * @param null $userId
     *
     * @return bool
     * @throws XhException
     *
     * create by dale  20180718
     */
   public static function prodIn($data , $keyMap=[] , $mark='' , $userId = null){
       $obj = new XHImsProduceIn();
       $obj->assign($data);
       foreach ($keyMap as $key => $map){
           $obj->$key = $data[$map];
       }
       $obj->mDesc = $obj->mDesc ?: $mark;
       if($userId){
           $obj->iCreateUserId     = $userId;
           $obj->iLastModifyUserId = $userId;
       }
       if (!$obj->save()){
           throw new XhException('入库保存失败');
       }
       //商品现库存量修改
       $prod = XHImsProduce::findFirst($obj->iProdId);
       $prod->iCurrentNum += $obj->iInNum;
       if (!$prod->save()) {
           throw new XhException('数量修改失败');
       }
       return true;
   }

    /**
     * 出库保存
     *
     * @param $data
     * @param array $keyMap
     * @param string $mark
     * @param null $userId
     *
     * @return bool
     * @throws XhException
     *
     * create by dale  20180718
     */
   public static function prodOut($data , $keyMap=[] , $mark='' , $userId = null){
       $obj = new XHImsProduceOut();
       $obj->assign($data);
       foreach ($keyMap as $key => $map){
           $obj->$key = $data[$map];
       }
       $obj->mDesc = $obj->mDesc ?: $mark;
       if($userId){
           $obj->iCreateUserId     = $userId;
           $obj->iLastModifyUserId = $userId;
       }
       if (!$obj->save()){
           throw new XhException('入库保存失败');
       }
       //商品现库存量修改
       $prod = XHImsProduce::findFirst($obj->iProdId);
       if ($prod->iProdAttr == 1){
           $prod->iCurrentNum -= $obj->iOutNum;
           if (!$prod->save()) {
               throw new XhException('数量修改失败');
           }
       } else if ($prod->iProdAttr == 2) {
           if ($prod->mParts) {
               foreach ($prod->mParts as $partAttr) {
                   $part = new XHImsProduceOut();
                   $part->iParentId = $obj->iPOutId;
                   $part->iProdId   = $partAttr['prodId'];
                   $part->iOutNum   = $partAttr['num'] * $obj->iOutNum;  //自定商品出库数量
                   if (!$part->save()) {
                       throw new XhException('部件入库保存失败');
                   }
                   $partProd = XHImsProduce::findFirst($partAttr['prodId']);
                   $partProd->iCurrentNum -= $part->iOutNum;
                   if (!$partProd->save()) {
                       throw new XhException('部件数量更新失败');
                   }
               }
           }
       }
       return true;
   }

    /**
     * 搜索商品名称
     *
     * @param $key
     * @param bool $withName
     *
     * @return array
     *
     * create by dale  20180725
     */
    public static function searchProduce($key, $withName = false)
    {
        $prods = XHImsProduce::getProds();
        $machIds = [];
        foreach ($prods as $prodId => $prodName ) {
            if (strpos($prodName, $key) !== false) {
                $machIds[$prodId] = $prodName;
            }
        }
        return $withName ? $machIds : array_keys($machIds);
    }


    /**
     * 添加设备id
     *
     * @param $obj
     * @param $fields
     *
     * @return bool
     *
     * create by dale  20180802
     */
    public static function runProdIdByName(&$obj, $fields)
    {
        if (!$obj || !$fields){
            return false;
        }
        is_string($fields) and $fields = [$fields => $fields];
        $prodIdArr = XHImsProduce::getProds();
        $prodIdArr = array_flip(array_map(function ($value){
            return trim($value);
        }, $prodIdArr));
        foreach($obj as $index => &$objOne){
            foreach($fields as $idField => $nameField){
                if (!isset($prodIdArr[trim($objOne[$idField])])) continue;

                $objOne[$nameField] = $prodIdArr[trim($objOne[$idField])];
            }
        }
        return true;
    }

    /**
     * 获取商品名称通过商品id
     *
     * @param $obj
     * @param $fields
     *
     * @return bool
     *
     * create by dale  20190123
     */
    public static function runProdNameById(&$obj, $fields)
    {
        if (!$obj || !$fields){
            return false;
        }
        is_string($fields) and $fields = [$fields => $fields];
        $prodIdArr = XHImsProduce::getProds();
        foreach($obj as $index => &$objOne){
            foreach($fields as $idField => $nameField){
                if (!isset($prodIdArr[trim($objOne[$idField])])) continue;
                $objOne[$nameField] = $prodIdArr[trim($objOne[$idField])];
            }
        }
        return true;
    }

    /**
     * 获取商品类型
     *
     * @return array|bool|mixed|null
     *
     * create by dale  20190114
     */
    public static function getProdType()
    {
        return XHImsProduceType::getProduceTypeEnum();
    }

    /**
     * 根据商品类型获取商品
     *
     * @param $typeId
     *
     * @return array
     * @throws \Exception
     *
     * create by dale  20190114
     */
    public static function getProdByTypeId($typeId)
    {
        if (!$typeId) {
            throw new \Exception('缺少typeId');
        }
        $prods = XHImsProduce::find([
            'columns'    => 'iProdId,sProdName',
            'conditions' => 'bDelete = 0 and iPTId = :iPTId:',
            'bind'       => ['iPTId' => $typeId]
        ])->toArray();
        if (!$prods) {
            return [];
        }
        return array_column($prods, 'sProdName', 'iProdId');
    }

    /**
     * 更新商品数目
     *
     * @param null $id
     * @throws \Exception
     *
     * create by dale  20180814
     */
    public static function uploadData($id = null){
        if ($id) {
            $obj = XHImsProduce::findFirst($id);
            if(!$obj){
                throw new \Exception('未找到商品');
            }
            $in = XHImsProduceIn::find([
                'conditions' => 'bDelete = 0 and iProdId = :iProdId:',
                'bind'    => ['iProdId' => $id]
            ])->toArray();
            $out = XHImsProduceOut::find([
                'conditions' => 'bDelete = 0 and iProdId = :iProdId:',
                'bind'    => ['iProdId' => $id]
            ])->toArray();
            $total = 0;
            if ($in) {
                foreach ($in as $row) {
                    $total += $row['iInNum'];
                }
            }
            if ($out) {
                foreach ($out as $row) {
                    $total -= $row['iOutNum'];
                }
            }
            $obj->iCurrentNum = $total;
            if (!$obj->save()) {
                throw new \Exception('保存失敗');
            }
        } else {
            $in = XHImsProduceIn::find([
                'conditions' => 'bDelete = 0 '
            ])->toArray();
            $out = XHImsProduceOut::find([
                'conditions' => 'bDelete = 0 '
            ])->toArray();
            $arr = [];
            foreach ($in as $row) {
                $arr[$row['iProdId']] = Tool::getValue($arr, $row['iProdId'], 0) + $row['iInNum'];
            }
            foreach ($out as $row) {
                $arr[$row['iProdId']] = Tool::getValue($arr, $row['iProdId'], 0) - $row['iOutNum'];
            }
            $prodArr = XHImsProduce::find([
                'conditions' => 'bDelete = 0'
            ]);
            foreach ($prodArr as $prod) {
                $prod->iCurrentNum = Tool::getValue($arr, $prod->iProdId, 0);
                if (!$prod->save()) {
                   throw new \Exception('保存失敗');
                }
            }
        }
    }

    /**
     * 根据商品名称获取信息
     *
     * @param $prodName
     *
     * @return array
     * @throws \Exception
     *
     * create by dale  20190124
     */
    public static function getProdInfoByName($prodName)
    {
        if (!$prodName) {
            throw new \Exception('缺少商品名称');
        }
        $prodName = trim($prodName);
        $prod = XHImsProduce::findFirst([
            'conditions' => 'bDelete = 0 and sProdName = :sProdName:',
            'bind'       => ['sProdName' => $prodName]
        ]);
        if (!$prod) {
            throw new \Exception('未找到商品信息');
        }
        return $prod->toArray();
    }

}